package cn.jdy.plugins.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.NginxPurgeCacheUtil;
import cn.jdy.plugins.entity.ExamOptions;
import cn.jdy.plugins.entity.ExamQuestions;
import cn.jdy.plugins.service.EvaluationProjectService;
import cn.jdy.plugins.service.ExamOptionsService;
import cn.jdy.plugins.service.ExamQuestionsService;


/**
 * @desc   测评试题管理控制操作类
 * @author nignqian
 * @date   2016-7-5
 */
@Controller
@RequestMapping("/examQuestions")
public class ExamQuestionsCtrl extends BaseCtrl {
	@Autowired
	private ExamQuestionsService examQuestionsService;
	
	@Autowired
	private ExamOptionsService examOptionsService;
	
	@Autowired
	private EvaluationProjectService evaluationProjectService;
	
	private static Long liveIds;
	
	//默认列表路径
	private static String viewName = "redirect:/examQuestions/list?s=";

	/**
	 * 初始化
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list( ExamQuestions entity, String fromDate,Long projectId ,Long liveId,String toDate, @RequestParam(required = false) Character s) {
		ModelAndView mv = new ModelAndView("/evaluationManage/examQuestionsList.jsp");
		
		if(s != null)
			switch(s) {
				case '1': mv.addObject("msg", "保存成功！");break;
				case '2': mv.addObject("msg", "更新成功！");break;
				case '3': mv.addObject("msg", "删除成功！");break;
				case '4': mv.addObject("msg", "操作失败！");break;
				default: break;
			}
		liveIds=liveId;
		mv.addObject("liveId", liveId);
		mv.addObject("projectId", projectId);
		mv.addObject("entity", entity);
		mv.addObject("fromDate", fromDate);
		mv.addObject("toDate", toDate);
		return mv;
	}
	
	
	
	
	/**
	 * 异步查询试题信息
	 * @param  examQuestions
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(ExamQuestions examQuestions, String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", examQuestionsService.query(examQuestions, fromDate, toDate));
			jsonMap.put("iTotalDisplayRecords", examQuestionsService.count(examQuestions, fromDate, toDate));
			jsonMap.put("iTotalRecords", examQuestionsService.count(examQuestions, fromDate, toDate));
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}	
	
	
	/**
	 * 异步查询所有测评标签
	 * @param  
	 * @return
	 */
	@RequestMapping("/queryAllLabel")
	@ResponseBody
	public Map<String, Object> queryAllLabel() {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
		//	jsonMap.put("dataList", this.evaluationLabelService.find("sort","1"));
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}	
	
	/**
	 * 异步查询所有项目
	 * @param  
	 * @return
	 */
	@RequestMapping("/queryAllProject")
	@ResponseBody
	public Map<String, Object> queryAllProject() {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", this.evaluationProjectService.findAll());
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}	
	
	
	/**
	 * 修改试题显示顺序
	 * @param  id,sort
	 * @return
	 */
	@RequestMapping("/updateSort")
	@ResponseBody
	public Map<String, Object> updateSort(@RequestParam("id") Long id,@RequestParam("sort") Integer sort) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String result = "0";  //0-成功 ,1-异常
		try {
			//获取要修改顺序的试题
			ExamQuestions examQuestions = this.examQuestionsService.find(id);
			if(null != examQuestions){
				examQuestions.setSort(sort);
				this.examQuestionsService.update(examQuestions);
			}
			// 清理缓存
			NginxPurgeCacheUtil.purge(2, id);
		} catch(Exception e) {
			BaseLog.e(getClass(), "修改异常！", e);
			result = "1";
		}
		jsonMap.put("result", result);
		return jsonMap;
	}

	
	

	/**
	 * 新增
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit(ExamQuestions examQuestions) {
		ModelAndView mv = new ModelAndView("/evaluationManage/examQuestionsDetail.jsp");
	//	mv.addObject("projectId", examQuestions.getProjectId());
		
		mv.addObject("datalists", evaluationProjectService.find("id",examQuestions.getProjectId()));

    
		mv.addObject("data", null== examQuestions.getId() || 0 == examQuestions.getId()  ? examQuestions.getId()  : this.examQuestionsService.find(examQuestions.getId() ));
		return mv;
	}

	/**
	 * 编辑
	 * @param id
	 * @return
	
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/evaluationManage/examQuestionsDetail.jsp");
		mv.addObject("data", null== id || 0 == id ? id : this.examQuestionsService.find(id));
		return mv;
	} */

	/**
	 * 保存（更新）试题信息
	 * @param examQuestions
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public ModelAndView save(ExamQuestions examQuestions) {
		ModelAndView mv = new ModelAndView();
		try {
			if(null == examQuestions.getId()) {

				
				//新增
				Integer maxSort = examQuestionsService.getMaxSort();//获取当前最大显示顺序
				examQuestions.setSort(maxSort+1);
				examQuestions.setInsertTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				this.examQuestionsService.save(examQuestions);
				
				mv.setViewName(this.viewName.concat("1"));
				mv.setViewName("redirect:/examQuestions/list?liveId="+liveIds+"&projectId="+examQuestions.getProjectId());

			} else {
				//修改
				examQuestions.setUpdateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				this.examQuestionsService.update(examQuestions);
				
				mv.setViewName(this.viewName.concat("2"));
				mv.setViewName("redirect:/examQuestions/list?liveId="+liveIds+"&projectId="+examQuestions.getProjectId());

		    // 清理缓存
		    NginxPurgeCacheUtil.purge(2, examQuestions.getId());
			}
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "保存异常！", e);
		}

		return mv;
	}
	

	/**
	 * 删除试题信息（先删除试题下的选项）
	 * @return
	 */
	@RequestMapping("/del/{id}")
	@ResponseBody
	public Map<String, Object> del(@PathVariable Long id) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			//获取试题下的选项
			List<ExamOptions> list = this.examOptionsService.find("questionId",id);
			if(null != list && 0< list.size()){
				for(ExamOptions examOptions : list){
					this.examOptionsService.delete(examOptions.getId());
				}
			}
			
			this.examQuestionsService.delete(id);
			jsonMap.put("msg", "成功");
			// 清理缓存
			NginxPurgeCacheUtil.purge(2, id);
		} catch(Exception e) {
			jsonMap.put("msg", "失败");
			BaseLog.e(getClass(), "删除异常！", e);
		}
		return jsonMap;
	}
}
